<template>
  <el-dialog
    title="新增用户"
    :visible.sync="dialogVisible"
    :before-close="cancel"
    :close-on-click-modal="false"
    :append-to-body="true"
    class="vc-dialog-form append-to-body"
    width="480px">

    <forms ref="addForm" :formConfig="formConfig" @change="changeData"/>

    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancel">取消</el-button>
      <el-button type="primary" size="small" :disabled="disabled" @click="save">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'addUser',
  props: {
    dialogVisible: {
      type: Boolean
    },
    subComponent: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var validateName = (rule, value, callback) => {
      this.$api.checkUsernameIsUsable({
        data: this.$refs.addForm.insideData
      }).then(res => {
        if (!res.success) {
          callback();
          return;
        }
        if (!res.data) {
          callback(new Error('该用户名已被使用'));
          return;
        }
        callback();
      }).catch(() => {
        callback();
      });
    };
    return {
      formConfig: {
        items: [
          {
            title: '用户名',
            key: 'username',
            maxlength: 20,
            required: true,
            message: '请输入用户名',
            self: validateName
          },
          {
            title: '昵称',
            key: 'nickname',
            maxlength: 10,
            required: true,
            message: '请输入昵称'
          },
          {
            title: '登录密码',
            key: 'cipherCode',
            type: 'text'
          },
          {
            title: '用户类型',
            key: 'type',
            type: 'select',
            group: this.$store.state.dic.listFormat['yhlx'],
            required: true,
            message: '请选择用户类型'
          },
          {
            title: '用户状态',
            key: 'state',
            type: 'select',
            group: this.$store.state.dic.listFormat['yhzt'],
            required: true,
            message: '请选择用户状态'
          },
          {
            title: '用户性质',
            key: 'nature',
            type: 'select',
            group: this.$store.state.dic.listFormat['yhxz'],
            required: true,
            message: '请选择用户性质',
            change: this.changeNature
          },
          {
            title: '有效时长',
            key: 'effectiveMonths',
            type: 'select',
            show: () => { return true },
            group: this.$store.state.dic.listFormat['effective_time'],
            required: true,
            message: '请选择有效时长'
          }
        ],
        params: {
          username: '',
          nickname: '',
          cipherCode: '',
          type: '',
          state: '',
          nature: '',
          effectiveMonths: ''
        }
      },
      disabled: false,
      currData: {}
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) return;
      this.disabled = false;
      this.initDefaultForm();
    }
  },
  methods: {
    /**
     * 初始化表单默认值
     */
    initDefaultForm() {
      this.formConfig.items[6].show = () => { return true };
      this.formConfig.params = {
        username: '',
        nickname: '',
        cipherCode: this.GLOBAL.pwdHandler.getRandomPwd(),
        type: this.GLOBAL.CONSTANTS.DEFAULT_USER_TYPE,
        state: this.GLOBAL.CONSTANTS.DEFAULT_USER_STATE,
        nature: this.GLOBAL.CONSTANTS.DEFAULT_USER_NATURE,
        effectiveMonths: this.GLOBAL.CONSTANTS.DEFAULT_USER_EFFECT_MON
      };
      this.$nextTick(() => { this.$refs.addForm && this.$refs.addForm.clearValidate(); });
    },
    /**
     * 保存
     */
    save() {
      if (this.disabled) {
        return;
      }
      this.$refs.addForm.save(() => {
        let msg = this.GLOBAL.pwdHandler.checkPwdByName(this.formConfig.params.cipherCode, this.formConfig.params.username);
        if (msg) {
          this.$confirmBox(() => {
            this.formConfig.params.cipherCode = this.GLOBAL.pwdHandler.getRandomPwd();
          }, `登录密码${msg}，确定重新生成登录密码吗？`);
          return;
        }
        this.disabled = true;
        this.$api.addUser({
          data: Object.assign({}, this.formConfig.params, {
            cipherCode: this.ENCRYPT.RSAencrypt(this.formConfig.params.cipherCode)
          })
        }).then(res => {
          if (!res.success) {
            this.disabled = false;
            return;
          }
          this.$emit('close', (this.subComponent ? res.data : true));
          !this.subComponent && this.$notifyBox('新增成功', 'success');
        }).catch(() => {
          this.disabled = false;
        });
      });
    },
    /**
     * 取消
     */
    cancel() {
      this.$emit('close', false);
    },
    /**
     * 表单数据改变事件
     */
    changeData(data) {
      this.currData = JSON.parse(JSON.stringify(data));
    },
    /**
     * '用户性质'改变事件
     */
    changeNature(val) {
      let isShow = val === this.GLOBAL.CONSTANTS.DEFAULT_USER_NATURE;
      this.formConfig.items[6].show = () => { return isShow };
      Object.assign(this.formConfig.params, this.currData, {
        nature: val,
        effectiveMonths: isShow ? this.GLOBAL.CONSTANTS.DEFAULT_USER_EFFECT_MON : ''
      });
      this.$forceUpdate();
    }
  }
}
</script>